//
//  PywFastRegisterAccountController.m
//  PywSdk
//
//  Created by smallwave on 16/9/21.
//  Copyright © 2016年 zero. All rights reserved.
//

#import "PywFastRegisterAccountController.h"
#import "UIButton+Pyw.h"
#import "UILabel+Pyw.h"
#import "UIImage+Pyw.h"
#import "PywTextFieldView.h"
#import "PywMasonry.h"
#import "PywFastRegisterApi.h"
#import "PywUser.h"
#import "PywPassportUtils.h"
#import "PywCPNotifications.h"
#import "PywSdk+login.h"
#import "PywRSAUtil.h"
#import "PywMBProgressHUD+Pyw.h"
#import "PywRealNameAuthManager.h"
#import "PywUploadAccountLoginManager.h"
#import "PywDisclaimerView.h"
#import "PywDisclaimerViewController.h"
#import "PywBuriedManager.h"

@interface PywFastRegisterAccountController ()<PywDisclaimerViewDelegate>

@property (nonatomic, strong) UILabel           *gameAccountLabel;
@property (nonatomic, strong) PywTextFieldView  *gamePasswordText;
@property (nonatomic, strong) UILabel           *reminderLabel;
@property (nonatomic, strong) UIButton          *enterGameButton;
@property (nonatomic, strong) PywDisclaimerView *disclaimerView;

@property (nonatomic, copy) NSString *account;
@property (nonatomic, copy) NSString *password;

@property (nonatomic, strong) PywFastRegisterApi *fastRegisterLoginApi;
@end

@implementation PywFastRegisterAccountController
KeyBoardHelper(90)

- (instancetype)initWithAccount:(NSString *)account
                       password:(NSString *)password{
    self = [super init];
    if (self) {
        self.account = account;
        self.password = password;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUp];
}
#pragma prepareUI
- (void)setUp{
    self.title = @"快速注册";
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self addSubviewAndLayoutSubviews];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"%s",__FUNCTION__);
    [PywBuriedManager manager].page_sn = @"2";
    [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"2" actionSn:@"1" typeSn:@"1"];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    NSLog(@"%s",__FUNCTION__);
    [PywBuriedManager manager].page_sn = @"";
//    [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"2" actionSn:@"2" typeSn:@"2"];
}
- (void)returnback
{
    [super returnback];
    [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"2" actionSn:@"7" typeSn:@"3"];
}
- (void)addSubviewAndLayoutSubviews{
    [self.view addSubview:self.gameAccountLabel];
    [self.view addSubview:self.gamePasswordText];
    [self.view addSubview:self.reminderLabel];
    [self.view addSubview:self.enterGameButton];
    [self.view addSubview:self.disclaimerView];
    
    __weak typeof(self) wSelf = self;
    [self.gameAccountLabel mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(wSelf.view.mas_top).offset(80);
        make.width.equalTo(wSelf.view.mas_width).multipliedBy(0.85);
    }];
    [self.gamePasswordText mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(wSelf.gameAccountLabel.mas_bottom).offset(20);
        make.width.equalTo(wSelf.gameAccountLabel.mas_width);
        make.height.equalTo(@40);
    }];
    [self.reminderLabel mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(wSelf.gamePasswordText.mas_bottom).offset(10);
        make.width.equalTo(wSelf.gamePasswordText.mas_width);
    }];
    [self.enterGameButton mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(wSelf.reminderLabel.mas_bottom).offset(20);
        make.width.height.equalTo(wSelf.gamePasswordText);
    }];
    [self.disclaimerView mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(wSelf.enterGameButton.mas_bottom).offset(10);
        make.width.height.equalTo(wSelf.gamePasswordText);
    }];
}
#pragma mark - Action
// 点击 进入游戏
- (void)selectEnterGameButtonAction:(UIButton *)sender{
    [self.view endEditing:YES];
    [self.gamePasswordText resignFirstResponder];
    
    if (self.gamePasswordText.text.length < 6) {
        [PywMBProgressHUD showError:@"密码不能低于6位"];
        return;
    }
    
    [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"2" actionSn:@"3" typeSn:@"3"];
    // 请求进入游戏
    WEAK_SELF;
    [self.fastRegisterLoginApi requestFastRegisterLoginWithFlag:FastRegisterFlag_Login
                                                        account:self.account
                                                       password:self.gamePasswordText.text
                                                        success:^(NSString *status, id anyObjct) {
                                                            // 保存数据后，发送通知
                                                            STRONG_SELF(weakSelf);
                                                            [strongSelf saveDataInfoWithDict:anyObjct];
                                                            
                                                        } fail:^(NSError *error) {
                                                            
                                                        }];
}
/**
 *  保存数据信息
 *
 *  @param dict <#dict description#>
 */
- (void)saveDataInfoWithDict:(NSDictionary *)dict{
    // 保存返回数据
    [PywPlatformMain sharedPlatformMain].uid = [NSString stringWithFormat:@"%@",dict[@"cp_uid"]];
    [PywPlatformMain sharedPlatformMain].token = [NSString stringWithFormat:@"%@",dict[@"token"]];
    
    // 保存用户模型
    PywUser *user = [[PywUser alloc] init];
    user.passport = self.account;
    user.password = [PywRSAUtil encryptString:self.gamePasswordText.text];
    [PywPassportUtils savePassport:user];
    
    [PywPlatformMain sharedPlatformMain].accountType = UserType_Account;
    [PywPlatformMain sharedPlatformMain].userName = user.passport;
    [PywPlatformMain sharedPlatformMain].account = user.passport;
    [PywPlatformMain sharedPlatformMain].account_pwd = user.password;
    
    // 保存登录的状态
    [PywPlatformMain sharedPlatformMain].logined = YES;
    [PywPlatformMain sharedPlatformMain].logouted = NO;
    [PywPlatformMain sharedPlatformMain].is_game_fast_login = YES;
    
    [self sendLoginSuccessNotification];
}

- (void)sendLoginSuccessNotification{
    /**
     *  发送“登录成功”通知
     */
    NSMutableDictionary *mDict = [[NSMutableDictionary alloc] init];
    [mDict setObject:[NSNumber numberWithInt:PYW_LOGIN_STATE_SUCCESS] forKey:@"result"];
    [mDict setObject:@"登录成功" forKey:@"info"];
    [mDict setObject:[PywPlatformMain sharedPlatformMain].account forKey:@"account"];
    [[NSNotificationCenter defaultCenter] postNotificationName:kPywCPLoginNotification object:nil userInfo:mDict];
    
    // Modal出“实名认证”控制器，加载Web端实名制认证
    [[PywRealNameAuthManager manager] showRealNameAuthViewController];
    
    /**
     *  发送“消除主登录页面”的通知 并 关闭控制器
     */
    MutableDictionary *param = [[MutableDictionary alloc] init];
    [param setObject:[NSNumber numberWithBool:YES] forKey:@"fastRegister"];
    [[NSNotificationCenter defaultCenter] postNotificationName:DidRegisterSuccess object:param];
    // 关闭控制器
    [self.navigationController dismissViewControllerAnimated:YES completion:NULL];
    
    // 登录成功，保存当前账号登录时间,并查询是否上传登录时长【备注：在登录状态View过程中，会再次调用。故此处去除上报】
//    [[PywUploadAccountLoginManager manager] uploadAccountLoginTimeLong];
}

#pragma mark - PywDisclaimerViewDelegate
- (void)didButton:(UIButton *)button index:(NSInteger)index
{
    if (index == ButtonTag_Disclaimer) { // 免责声明
        
        PywDisclaimerViewController *disclaimerVC = [[PywDisclaimerViewController alloc] init];
        [self presentViewController:disclaimerVC animated:YES completion:NULL];
    }else{
        
        if (!button.selected) {
            self.enterGameButton.enabled = YES;
            [self.enterGameButton setBackgroundColor:UIColorFromRGB(0xFFBC00)];
        }else{
            self.enterGameButton.enabled = NO;
            [self.enterGameButton setBackgroundColor:[UIColor lightGrayColor]];
        }
    }
}

#pragma mark - Lazy
- (UILabel *)gameAccountLabel{
    if (!_gameAccountLabel) {
        NSString *gameMsg = [NSString stringWithFormat:@"游戏账号: %@",self.account];
        _gameAccountLabel = [UILabel labelWithText:gameMsg
                                     textAlignment:NSTextAlignmentLeft
                                          fontSize:12
                                         textColor:UIColorFromRGB(0x333333)];
    }
    return _gameAccountLabel;
}
- (PywTextFieldView *)gamePasswordText{
    if (!_gamePasswordText) {
        _gamePasswordText = [PywTextFieldView passwordTextFieldWithLeftImg:@"icon_password_normal"
                                                           TextPlaceholder:@"请输入登录密码(限6-12位)"
                                                           ButtonNormalImg:nil
                                                         ButtonSelectedImg:nil];
        _gamePasswordText.secureTextEntry = NO;
        _gamePasswordText.text = self.password;
        [_gamePasswordText setAccessibilityId:@"fast_loginpswd"];
    }
    return _gamePasswordText;
}
- (UILabel *)reminderLabel{
    if (!_reminderLabel) {
        _reminderLabel = [UILabel labelWithText:@"为方便记忆，可输入新密码"
                                  textAlignment:NSTextAlignmentLeft
                                       fontSize:12
                                      textColor:UIColorFromRGB(0x999999)];
    }
    return _reminderLabel;
}
- (UIButton *)enterGameButton{
    if (!_enterGameButton) {
        _enterGameButton = [UIButton buttonWithBackgroundColor:UIColorFromRGB(0xFFBC00)
                                                  cornerRadius:20
                                                    titleColor:[UIColor whiteColor]
                                            titleLabelFontSize:18
                                                         title:@"进入游戏"];
        [_enterGameButton addTarget:self action:@selector(selectEnterGameButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_enterGameButton setAccessibilityIdentifier:@"fast_logingame"];
    }
    return _enterGameButton;
}
- (PywDisclaimerView *)disclaimerView
{
    if (!_disclaimerView) {
        _disclaimerView = [[PywDisclaimerView alloc] initWithDelegate:self];
    }
    return _disclaimerView;
}
- (PywFastRegisterApi *)fastRegisterLoginApi{
    if (!_fastRegisterLoginApi) {
        _fastRegisterLoginApi = [PywFastRegisterApi manager];
    }
    return _fastRegisterLoginApi;
}

@end
